package com.aynu.gulimall.product.web;

import com.aynu.gulimall.product.entity.CategoryEntity;
import com.aynu.gulimall.product.service.CategoryService;
import com.aynu.gulimall.product.vo.Catalog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author mj
 * @version 1.0
 * @date 2021/3/9 21:30
 */
@Controller
@Slf4j
public class IndexController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedissonClient redisson;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping({"index.html","/"})
    public String indexPage(Model model){

        Long level = 0L;

        log.info("查出所有的一级分类");
        List<CategoryEntity> categorys = categoryService.getLevelCategory(level);

        model.addAttribute("categorys",categorys);
        //视图解析器进行拼串
        return "index";
    }

    @GetMapping("index/catalog.json")
    @ResponseBody
    public Map<String, List<Catalog2Vo>> getCatalogJson(){
        Map<String, List<Catalog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }

    @GetMapping("/hello")
    @ResponseBody
    public String jianDan(){
        return "hello";
    }

    @GetMapping("/write")
    @ResponseBody
    public String write(){

        RReadWriteLock readWriteLock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = readWriteLock.writeLock();
        String uuid = "";
        try {
            rLock.lock();
            uuid = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set("test",uuid);
            Thread.sleep(30000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }

        return uuid;
    }

    @GetMapping("/read")
    @ResponseBody
    public String read(){

        //保证能一定能最新数据，修改期间，写锁是一个排他锁（互斥锁），读锁是一个共享锁
        //写锁没释放，读锁一直等待
        //写 + 写：阻塞
        //写 + 读：读等待
        //读 + 读：相当于无锁，并发读只会在redis中记录，所有当前的锁，他们都会同时加锁成功
        //读 + 写：写等待
        RReadWriteLock readWriteLock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = readWriteLock.readLock();
        String uuid = "";
        try {
            rLock.lock();
            uuid = redisTemplate.opsForValue().get("test");
            Thread.sleep(30000L);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }

        return uuid;
    }

    @GetMapping("/lock")
    @ResponseBody
    public String lock(){
        //1、获取一把锁
        RLock lock = redisson.getLock("my-lock");
        //2、加锁
        log.info("加锁成功，执行代码");//阻塞式等待
        lock.lock();
        //1）、锁的自动续期，如果业务过长，运行期间自动给锁序上新的30s，不用担心业务时间过长，锁自动过期会删掉
        //2)、加锁的业务只要运行完成，就不会给当前锁续期，即使不手动解锁，锁默认在30s以后自动删除

        //lock.lock(10, TimeUnit.SECONDS);//10秒自动解锁，使用此方法时，时间过了不会进行自动续期
        //1、如果我们传递了锁的超时时间，就发送给redis执行脚本，进行占锁，默认超时时间就是我们指定的时间
        //2、如果未指定超时时间，，默认使用看门狗的时间（30 * 1000）30秒【LockWatchdogTimeout】
        //  并且会开启一个定时任务，去更新锁的过期时间，更新为【LockWatchdogTimeout】（30秒）
        //  internalLockLeaseTime / 3L,3分之一时间（10秒），重新设置时间

        //最佳实战，
        //1)、lock.lock(10, TimeUnit.SECONDS)；需要手动解锁
        try {
            Thread.sleep(30000L);
            log.info("当前线程，{}",Thread.currentThread().getId());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        return "hello";
    }

    /**
     * 放假，锁门
     * 1、5个班全部走完，才能关锁
     * @return
     */
    @GetMapping("/lockDoor")
    @ResponseBody
    public String countDownLatch() throws InterruptedException {
        RCountDownLatch countdown = redisson.getCountDownLatch("countdown");
        countdown.trySetCount(5L);
        countdown.await();

        return "放假了。。。。。";
    }

    @GetMapping("/chu/{id}")
    @ResponseBody
    public String countDownLatch(@PathVariable("id") Long id){
        RCountDownLatch countdown = redisson.getCountDownLatch("countdown");
        try {
            countdown.countDown();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "班级"+id+"走了";
    }

    /**
     * 信号量
     * 举例：
     * 车库停车
     * 3个车位(默认)
     * @return
     */
    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {
        RSemaphore semphore = redisson.getSemaphore("semphore");
        //semphore.acquire();//获取一个信号量，获取一个值，占一个车位
        //尝试获取一个信号量，获取成功返回true
        boolean b = semphore.tryAcquire();

        //信号量可以进行分布式限量操作
        if (b){
            return "执行业务-->"+true;
        }else {
            return "error--->"+false;
        }
    }

    @GetMapping("/go")
    @ResponseBody
    public String go() throws InterruptedException {
        RSemaphore semphore = redisson.getSemaphore("semphore");
        semphore.release();//释放一个信号量，释放一个车位
        return "ok";
    }
}
